using System;

namespace Miao
{
    /// <summary>
    /// 表示一个正在运行的协程
    /// </summary>
    public class RunningCoroutine : CustomCoroutineWait
    {
        /// <summary>
        /// 协程运行结束事件接口
        /// </summary>
        public event Action onComplete;

        /// <summary>
        /// 当协程运行结束时.
        /// 无论协程是否完整结束,都会被调用
        /// </summary>
        internal Action onStop;

        /// <summary>
        /// 内部协程引用
        /// </summary>
        internal CoroutineInternal coroutineInternal;

        /// <summary>
        /// 停止协程
        /// </summary>
        public void Stop()
        {
            if (coroutineInternal && !coroutineInternal.isFinish)
            {
                onStop?.Invoke();
                CoroutineStarter.RemoveInternal(coroutineInternal);
                coroutineInternal = null;
            }
        }

        /// <summary>
        /// 完成协程
        /// </summary>
        internal void Complete()
        {
            onStop?.Invoke();
            coroutineInternal = null;
            onComplete?.Invoke();
        }
        /// <summary>
        /// 父级停止
        /// </summary>
        internal void ParentStop()
        {
            onStop?.Invoke();
            coroutineInternal = null;
        }

        public override bool Next()
        {
            return coroutineInternal == null;
        }

        public static implicit operator bool(RunningCoroutine self)
        {
            return self != null;
        }
    }
}